package com.xsnet.service.impl;

import com.xsnet.dto.UserDTO;
import com.xsnet.jooq.tables.TUser;
import com.xsnet.jooq.tables.records.TUserRecord;
import com.xsnet.service.UserService;
import org.jooq.DSLContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: springboot-jooq-demo
 * @description: 用户实现类
 * @author: Jamie.shi
 * @create: 2020-05-20 19:07
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private DSLContext dsl;

    @Override
    public void addUser(String mobile, String password) {
        TUserRecord record = new TUserRecord();
        record.setUsername(mobile);
        record.setPassword(password);
        record.setMobile(mobile);
        dsl.executeInsert(record);
    }

    @Override
    public void updateUserPassword(String password) {
        dsl.update(TUser.T_USER)
                .set(TUser.T_USER.PASSWORD, password)
                .set(TUser.T_USER.UPDATE_TIME, OffsetDateTime.now()).execute();
    }

    @Override
    public void deleteUser(String userName) {
        dsl.delete(TUser.T_USER).where(TUser.T_USER.USERNAME.eq(userName)).execute();
    }

    @Override
    public List<UserDTO> queryUser() {
        var list = dsl.selectFrom(TUser.T_USER).fetch();
        List<UserDTO> userDTOList = new ArrayList<>();
        list.stream().forEach(r -> {
            UserDTO dto = new UserDTO();
            BeanUtils.copyProperties(r, dto);
            userDTOList.add(dto);
        });
        return userDTOList;
    }
}
